package com.fangdada.demowebfulx2.handler;

import com.fangdada.demowebfulx2.entity.User;
import com.fangdada.demowebfulx2.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.servlet.ServletException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @Author: fd
 * @Date 2021/11/30 10:38
 * @Description: SpringWebflux（基于函数式编程模型）
 */
public class UserHandler {

	private final UserService userService;

	public UserHandler(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 根据ID查询
	 * @author fd
	 * @date 2021/11/30 10:40
	 * @param request
	 * @return reactor.core.publisher.Mono<org.springframework.web.servlet.function.ServerResponse>
	 */
	public Mono<ServerResponse> getUserById(ServerRequest request) {
		//获取 id 值
		int userId = Integer.parseInt(request.pathVariable("id"));
		//空值处理
		Mono<ServerResponse> notfound = ServerResponse.notFound().build();
		//调用 service 方法得到数据
		Mono<User> userMono = userService.getUserById(userId);
		//把 userMono 进行转换返回
		//使用 Reactor 操作符 flatMap
		Mono<ServerResponse> responseMono =
				userMono.flatMap(user -> ok()
				.contentType(MediaType.APPLICATION_JSON)
				.body(user, User.class)).switchIfEmpty(notfound);
		return responseMono;
	}

	/**
	 * 查询所有的用户
	 * @author fd
	 * @date 2021/11/30 15:18
	 * @return reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>
	 */
	public Mono<ServerResponse> getAllUser(ServerRequest request){
		Flux<User> allUser = userService.getAllUser();
		return ok().contentType(MediaType.APPLICATION_JSON).body(allUser,User.class);
	}

	/**
	 * 添加用户
	 * @author fd
	 * @date 2021/11/30 15:23
	 * @param request
	 * @return reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>
	 */
	public Mono<ServerResponse> saveUser(ServerRequest request) throws ServletException, IOException {
		User user = request.body(User.class);
		Mono<User> userMono = null;
		return ok().build(userService.saveUserInfo(userMono));
	}

}
